package design_pattern.TwoPhaseTermination;

import design_pattern.SingleThreadExecute.Client;
import org.omg.CORBA.PUBLIC_MEMBER;

import java.io.IOException;
import java.io.StringReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/18 14:30
 * @Version 1.0
 */
public class AppServer extends Thread {
    private int port;
    private static final int DEFAULT_PORT = 12722;
    private volatile boolean start = true;
    //这里是任务队列
    private List<ClientHandler> clientHandlers = new ArrayList<>();

    private final static ExecutorService executor = Executors.newFixedThreadPool(10);



    public AppServer(){
        this(DEFAULT_PORT);
    }
    public AppServer(int port){
        this.port = port;
    }

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(port);
            // 这个方法会阻塞住
            serverSocket.accept();
            while (start){
                //重点。这里的Socket 是新建任务（ClientHandler）中的一个子参数。
                Socket client = new Socket();
                ClientHandler clientHandler = new ClientHandler(client);
                executor.submit(clientHandler);
                this.clientHandlers.add(clientHandler);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //当自己被关闭的时候做一些清理（这部比较关键）
            this.dispose();
        }
    }

    private void dispose() {
        //把socket关闭。
        //把所有的 socket连接 给stop掉
        clientHandlers.stream().forEach(s->s.stop());
        //把线程池给关闭。
        executor.shutdown();
    }

    public void shutdown(){
        this.start = false;
        this.interrupt();
    }
}
